package net.narusas.aceauction.push.db;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.StatementCallback;

import net.narusas.aceauction.push.model.Device;
import net.narusas.util.lang.NFile;

import lombok.Data;

@Data
public class GoodsSearchDAO {
	DataSource dataSource;

	public GoodsSearchDAO() {

	}

	void initSQL() {

	}

	String loadSQL() {
		File f = new File("cfg/badge.sql");
		try {
			return NFile.getText(f, "UTF-8");
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

	public String generateSQL(String template, Map<String, Object> map) {
		String res = template;

		Pattern placeHolderPattern = Pattern.compile("(\\$\\{[^\\}]+\\})");
		Pattern bodyPattern = Pattern.compile("\\$\\{([^\\}]+)\\}");

		Matcher placeHolderMatcher = placeHolderPattern.matcher(template);
		while (placeHolderMatcher.find()) {
			String placeHolder = placeHolderMatcher.group(1);
			Matcher bodyMatcher = bodyPattern.matcher(placeHolder);
			bodyMatcher.find();// must be exists
			String[] tokens = bodyMatcher.group(1).split(" ");
			String temp = "";
			for (String token : tokens) {
				if (map.containsKey(token)) {
					temp += map.get(token) + " ";
				}
			}
			res = res.replace(placeHolder, temp.trim());

		}
		return res;
	}

	public String generateSQL(Device device) {
		String sql =generateSQL(loadSQL(), device.toMap());
		System.out.println(sql);
		return sql;
	}

	public int badgeOf(final Device device) {
		JdbcTemplate template = new JdbcTemplate();
		template.setDataSource(dataSource);
		RuntimeException e = null;
		for (int i = 0; i < 3; i++) {
			try {
				return template.execute(new StatementCallback<Integer>() {
					@Override
					public Integer doInStatement(Statement stmt) throws SQLException, DataAccessException {
						ResultSet rs = stmt.executeQuery(generateSQL(device));
						int badgeCount = 0;
						if (rs.next()) {
							badgeCount = rs.getInt(1);
						}
						return badgeCount;
					}
				});
			} catch (RuntimeException ex) {
				ex.printStackTrace();
				e = ex;
			}
		}
		throw e;
	}

}

